package cn.com.yang.nio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 直接缓冲区
 * @Author 杨亿金
 * @Date 2021/12/19 20:23
 * @CopyRight
 * @Version
 */
public class DirectBuffer {
    /**
     * 直接缓冲区是为了加快I/O速度
     * @param args
     */
    public static void main(String[] args) {
        //先从磁盘读取文件
        String readFile = "E://test.txt";
        try (FileInputStream inputStream = new FileInputStream(readFile);) {
            FileChannel channel = inputStream.getChannel();
            //把读取的内容写入到一个新文件
            String outFile = String.format("E://test_copy.txt");
            FileOutputStream outputStream = new FileOutputStream(outFile);
            FileChannel fout = outputStream.getChannel();
            //使用allocateDirect
            ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
            while (true){
                buffer.clear();
                int r = channel.read(buffer);
                if (r==-1){
                    break;
                }
                buffer.flip();
                fout.write(buffer);
            }
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
